package ru.tatintec.gwttest.client.presenter;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import ru.tatintec.gwttest.client.service.ServiceHelper;
import ru.tatintec.gwttest.client.view.CreateEditDialog;
import ru.tatintec.gwttest.shared.Employee;
import ru.tatintec.gwttest.shared.Employee.Sex;

public class CreateEditPresenter {

	CreateEditDialog createEditDialog; 
	
	public void create(final AsyncCallback<Void> asyncCallback) {
		createEditDialog = new CreateEditDialog("Create dialog");
		createEditDialog.setOkHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (! validated()) return;
				Employee employee = new Employee();
				employee.setLastName(createEditDialog.getLnTextBox().getText().trim());
				employee.setFirstName(createEditDialog.getFnTextBox().getText().trim());
				employee.setMiddleName(createEditDialog.getMnTextBox().getText().trim());
				employee.setBirthday(createEditDialog.getBirthdayBox().getValue());
				employee.setEmploymentDate(createEditDialog.getEmploymentBox().getValue());

				Sex sex = Sex.OTHER;
				if (createEditDialog.getSexMaleRadio().getValue()) {
					sex = Sex.MALE;
				}
				if (createEditDialog.getSexFemaleRadio().getValue()) {
					sex = Sex.FEMALE;
				}
				employee.setSex(sex);
				
				ServiceHelper.getEmployeeCatalogService().createEmployee(employee, asyncCallback);
				lockDialog();
			}
		});
		createEditDialog.center();
	}

	

	public void edit(final Employee employee, final AsyncCallback<Void> asyncCallback) {
		createEditDialog = new CreateEditDialog("Edit dialog");
		createEditDialog.initEditDialog(employee);
		createEditDialog.setOkHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (! validated()) return;
				employee.setLastName(createEditDialog.getLnTextBox().getText().trim());
				employee.setFirstName(createEditDialog.getFnTextBox().getText().trim());
				employee.setMiddleName(createEditDialog.getMnTextBox().getText().trim());
				employee.setBirthday(createEditDialog.getBirthdayBox().getValue());
				employee.setEmploymentDate(createEditDialog.getEmploymentBox().getValue());
				
				Sex sex = Sex.OTHER;
				if (createEditDialog.getSexMaleRadio().getValue()) {
					sex = Sex.MALE;
				}
				if (createEditDialog.getSexFemaleRadio().getValue()) {
					sex = Sex.FEMALE;
				}
				employee.setSex(sex);
				
				ServiceHelper.getEmployeeCatalogService().updateEmployee(employee, asyncCallback);
				lockDialog();
			}
		});
		createEditDialog.center();
	}

	protected boolean validated() {
		// TODO Auto-generated method stub
		return true;
	}

	public void lockDialog() {
		// TODO Auto-generated method stub
		
	}

	
	public void unlockDialog() {
		// TODO Auto-generated method stub
		
	}

	public void close() {
		createEditDialog.hide();
	}
	
}
